﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using Newtonsoft.Json.Linq;

namespace XXX.Common
{
    public class ComFunc
    {
        #region JObject
        public static string GetInfoFromJObject(JObject obj, string attrName, string defaultvalue = "")
        {
            string re = defaultvalue;
            try
            {
                if (obj.Property(attrName) != null && obj.Property(attrName).ToString() != "" && (!string.IsNullOrEmpty(obj[attrName].ToString())))
                {
                    re = obj[attrName].ToString().Trim();
                }
            }
            catch { }
            return re;
        }

        public static int GetIntInfoFromJObject(JObject obj, string attrName, int defaultvalue = -1)
        {
            int re = defaultvalue;
            try
            {
                if (obj.Property(attrName) != null && obj.Property(attrName).ToString() != "" && int.TryParse(obj[attrName].ToString(), out _))
                {
                    re = Convert.ToInt32(obj[attrName].ToString());
                }
            }
            catch { }
            return re;
        }

        public static DateTime GetDateTimeInfoFromJObject(JObject obj, string attrName)
        {
            DateTime re = new DateTime(1970, 1, 1, 0, 0, 0, 0);
            try
            {
                if (obj.Property(attrName) != null && obj.Property(attrName).ToString() != "" && DateTime.TryParse(obj[attrName].ToString(), out _))
                {
                    re = Convert.ToDateTime(obj[attrName].ToString());
                }
            }
            catch { }
            return re;
        }

        public static DateTime? GetDateTimeNullInfoFromJObject(JObject obj, string attrName)
        {
            DateTime? re = null;
            try
            {
                if (obj.Property(attrName) != null && obj.Property(attrName).ToString() != "" && DateTime.TryParse(obj[attrName].ToString(), out _))
                {
                    re = Convert.ToDateTime(obj[attrName].ToString());
                }
            }
            catch { }
            return re;
        }


        public static decimal GetDecimalInfoFromJObject(JObject obj, string attrName, decimal defaultvalue = 0)
        {
            decimal re = defaultvalue;
            try
            {
                if (obj.Property(attrName) != null && obj.Property(attrName).ToString() != "" && obj[attrName].ToString() != "")
                {
                    re = Convert.ToDecimal(obj[attrName].ToString());
                }
            }
            catch { }
            return re;
        }

        #endregion JObject

        #region 时间戳

        /// <summary>  
        /// 获取毫秒时间戳  13位
        /// </summary>  
        /// <returns></returns>  
        public static string GetTimeStamp_MS(DateTime dtime)
        {
            TimeSpan ts = dtime.ToUniversalTime() - new DateTime(1970, 1, 1, 0, 0, 0, 0);
            return Convert.ToInt64(ts.TotalMilliseconds).ToString().PadLeft(13, '0');
        }

        /// <summary>  
        /// 获取秒时间戳
        /// </summary>  
        /// <returns></returns>  
        public static string GetTimeStamp_S(DateTime dtime)
        {
            TimeSpan ts = dtime.ToUniversalTime() - new DateTime(1970, 1, 1, 0, 0, 0, 0);
            return Convert.ToInt64(ts.TotalSeconds).ToString().PadLeft(10, '0');
        }

        /// <summary>
        /// 毫秒时间戳转时间
        /// </summary>
        /// <param name="timeStamp"></param>
        /// <returns></returns>
        public static DateTime StampToDateTime_MS(string timeStamp)
        {
            try
            {
                DateTime dateTimeStart = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1));
                long lTime = long.Parse(timeStamp + "0000");
                TimeSpan toNow = new TimeSpan(lTime);

                return dateTimeStart.Add(toNow);
            }
            catch (Exception ex)
            {
                ExLog.WriteException("Func-StampToDateTime_MS\r\n" + ex.ToString());
                //WriteLog.Write_Log_Abnormal("Func-StampToDateTime_MS", ex.ToString());
                return DateTime.Now;
            }
        }

        /// <summary>
        /// 秒时间戳转时间
        /// </summary>
        /// <param name="timeStamp"></param>
        /// <returns></returns>
        public static DateTime StampToDateTime_S(string timeStamp)
        {
            DateTime dateTimeStart = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1));
            long lTime = long.Parse(timeStamp + "0000000");
            TimeSpan toNow = new TimeSpan(lTime);

            return dateTimeStart.Add(toNow);
        }

        #endregion 时间戳

        #region 正则

        /// <summary>
        /// 获取字符串中所有数字
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static string GetNum(string str)
        {

            Regex r = new Regex("\\d+\\.?\\d*");
            bool ismatch = r.IsMatch(str);
            MatchCollection mc = r.Matches(str);

            string result = string.Empty;
            for (int i = 0; i < mc.Count; i++)
            {
                result += mc[i];//匹配结果是完整的数字，此处可以不做拼接的
            }
            return result;
        }

        /// <summary>
        /// 获取字符串中所有字母
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static string GetAZ(string str)
        {
            Regex r = new Regex(@"[a-zA-Z]+");
            bool ismatch = r.IsMatch(str);
            MatchCollection mc = r.Matches(str);

            string result = string.Empty;
            for (int i = 0; i < mc.Count; i++)
            {
                result += mc[i];
            }
            return result;
        }

        #endregion 正则

        #region Time

        /// <summary>
        /// 秒转成 时分秒
        /// </summary>
        /// <param name="seconds"></param>
        /// <returns></returns>
        public static string SecondToTime(int seconds)
        {
            TimeSpan ts = new TimeSpan(0, 0, seconds);
            if (ts.TotalDays >= 1)
            {
                return ((int)ts.TotalDays) + "天" + ts.Hours.ToString() + "小时 " + ts.Minutes.ToString() + "分钟 " + ts.Seconds + "秒";
            }
            else
            {
                return ts.Hours.ToString() + "小时 " + ts.Minutes.ToString() + "分钟 " + ts.Seconds + "秒";
            }
        }

        /// <summary>
        /// 分转时分秒
        /// </summary>
        /// <param name="leaveTm"></param>
        /// <returns></returns>
        public static string MinToTime(int leaveTm)
        {
            //停留时间
            string TmSum = string.Empty;

            try
            {
                int day = 0;
                int hour = 0;
                int min = 0;

                day = leaveTm / 1440;
                hour = (leaveTm - (day * 1440)) / 60;
                min = (leaveTm - ((hour * 60) + (day * 1440)));

                if (day > 0)
                {
                    TmSum = day + "天";
                }
                if (hour > 0)
                {
                    TmSum += hour + "小时";
                }
                if (min > 0)
                {
                    TmSum += min + "分钟";
                }

            }
            catch
            {
                TmSum = leaveTm + "分钟";
            }

            return TmSum;
        }

        #endregion Time

        #region Money

        /// <summary>
        /// 金钱 分转元
        /// </summary>
        /// <param name="amount"></param>
        /// <returns></returns>
        public static string MonToString(int? amount)
        {
            decimal d = ((decimal)(amount ?? 0)) / 100;
            return d.ToString("0.00");
        }

        #endregion Money

        #region =加密=       

        ///<summary>
        ///给一个字符串进行MD5加密
        ///</summary>
        ///<param name="strText">待加密字符串</param>
        ///<returns>加密后的字符串</returns>
        public static string MD5Encrypt(string strText)
        {
            using (MD5 md5 = new MD5CryptoServiceProvider())
            {
                byte[] result = md5.ComputeHash(System.Text.Encoding.UTF8.GetBytes(strText));
                return Convert.ToBase64String(result);
            }
        }

        public static string MD5Encrypt_Hex(string md5str)
        {
            MD5 md5 = MD5.Create();
            var bs = md5.ComputeHash(Encoding.UTF8.GetBytes(md5str));
            var sb = new StringBuilder();
            foreach (byte b in bs)
            {
                sb.Append(b.ToString("x2"));
            }
            string sign = sb.ToString();
            return sign;
        }
        #endregion     

        /// <summary>
        /// 根据ASCII码从小到大排序（字典序）
        /// </summary>
        /// <param name="paramsMap"></param>
        /// <param name="iType">0:Query型连接 1:无连接参数</param>
        /// <returns></returns>
        public static String GetParamSrc(Dictionary<string, string> paramsMap, int iType = 0)
        {
            var vDic = (from objDic in paramsMap orderby objDic.Key ascending select objDic);
            StringBuilder str = new StringBuilder();
            String result = String.Empty;
            if (iType == 1)
            {
                foreach (KeyValuePair<string, string> kv in vDic)
                {
                    string pkey = kv.Key;
                    string pvalue = kv.Value;
                    str.Append(pkey + pvalue);
                }
                result = str.ToString();
            }
            else
            {
                foreach (KeyValuePair<string, string> kv in vDic)
                {
                    string pkey = kv.Key;
                    string pvalue = kv.Value;
                    str.Append(pkey + "=" + pvalue + "&");
                }
                result = str.ToString().Substring(0, str.ToString().Length - 1);
            }
            return result;
        }

        #region Datatable 

        public static string CellGetString(DataRow dr, string colName, string defaultvalue = "")
        {
            if (dr.Table.Columns.Contains(colName))
            {
                return dr[colName] == null ? defaultvalue : dr[colName].ToString().Trim();
            }
            else
            {
                return defaultvalue;
            }
        }

        #endregion Datatable

    }

}
